<template>
    <div ref="counterRef" class="counter-container">
        <div class="counter-number">{{ animatedNumber }}</div>
        <div class="counter-text">{{ text }}</div>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, defineProps } from 'vue'
const props = defineProps({
    number: {
        type: Number,
        required: true,
    },
    text: {
        type: String,
        required: true,
    },
    duration: {
        type: Number,
        default: 2000,
    },
})

const counterRef = ref(null)
const animatedNumber = ref(0)
let observer = null

onMounted(() => {
    startObserver()
})

onUnmounted(() => {
    if (observer) {
        observer.disconnect()
    }
})

const animateNumber = () => {
    const startTime = Date.now()
    const endNumber = props.number

    const updateNumber = () => {
        const currentTime = Date.now()
        const progress = Math.min((currentTime - startTime) / props.duration, 1)
        animatedNumber.value = Math.floor(progress * endNumber)

        if (progress < 1) {
            requestAnimationFrame(updateNumber)
        }
    }

    requestAnimationFrame(updateNumber)
}

const startObserver = () => {
    observer = new IntersectionObserver(
        (entries) => {
            entries.forEach((entry) => {
                if (entry.isIntersecting) {
                    animateNumber()
                    observer.unobserve(counterRef.value) // 动画触发后停止监听
                }
            })
        },
        {
            threshold: 0.5, // 当元素 50% 进入视口时触发
        }
    )

    observer.observe(counterRef.value)
}
</script>

<style scoped>
.counter-container {
    text-align: center;
    margin: 20px 0;
}

.counter-number {
    font-size: 48px;
    font-weight: bold;
    color: #409eff;
}

.counter-text {
    font-size: 16px;
    color: #666;
    margin-top: 10px;
}
</style>
